{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# 4 Pandas的索引操作"
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "##### 1. Series 和 DataFrame 中的索引都是 Index 对象"
  },
  {
   "cell_type": "code",
   "source": [
    "import pandas as pd\n",
    "import numpy as np"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-17T04:43:34.739013Z",
     "start_time": "2025-01-17T04:43:34.491036Z"
    }
   },
   "outputs": [],
   "execution_count": 1
  },
  {
   "cell_type": "code",
   "source": [
    "dict_data = {'A': 1,\n",
    "             'B': pd.Timestamp('20190926'),\n",
    "             'C': pd.Series(1, index=list(range(4)),dtype='float32'),\n",
    "             'D': np.array([1,2,3,4],dtype='int32'),\n",
    "             'E': [\"Python\",\"Java\",\"C++\",\"C\"],\n",
    "             'F': 'wangdao' }\n",
    "df_obj2 = pd.DataFrame(dict_data)\n",
    "ser_obj = pd.Series(range(10, 20))\n",
    "\n",
    "print(type(ser_obj.index))\n",
    "print(type(df_obj2.index))\n",
    "\n",
    "print(df_obj2.index)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-01-17T04:45:14.597165Z",
     "start_time": "2025-01-17T04:45:14.593680Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.indexes.range.RangeIndex'>\n",
      "<class 'pandas.core.indexes.base.Index'>\n",
      "Index([0, 1, 2, 3], dtype='int64')\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "##### 2. 索引对象的值不可变（上面代码增加）"
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [],
   "source": "# df_obj2.index[0] = 2",
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "##### 3.常见的Index种类\n",
    "- Index，索引  可以是各种类型\n",
    "- Int64Index，整数索引\n",
    "- MultiIndex，层级索引，难度较大\n",
    "- DatetimeIndex，时间戳类型"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "source": [
    "# 1. index 指定行索引名\n",
    "ser_obj = pd.Series(range(5), index = list(\"abcde\"))\n",
    "print(ser_obj)\n",
    "ser_obj.index"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-01-17T04:48:42.253409Z",
     "start_time": "2025-01-17T04:48:42.249269Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    0\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "e    4\n",
      "dtype: int64\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "Index(['a', 'b', 'c', 'd', 'e'], dtype='object')"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 5
  },
  {
   "cell_type": "code",
   "source": [
    "# 行索引，不仅可以用索引名，可以用索引位置或来取\n",
    "# 不规范写法\n",
    "print(ser_obj['b']) # 按照索引名\n",
    "print(ser_obj[2]) # 按照位置索引"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-01-17T04:49:50.904559Z",
     "start_time": "2025-01-17T04:49:50.901945Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Administrator\\AppData\\Local\\Temp\\ipykernel_28616\\3364452059.py:4: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`\n",
      "  print(ser_obj[2]) # 按照位置索引\n"
     ]
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T04:50:24.445770Z",
     "start_time": "2025-01-17T04:50:24.443482Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 规范写法\n",
    "print(ser_obj.loc['b']) # 索引名\n",
    "print(ser_obj.iloc[2]) # 位置索引"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n"
     ]
    }
   ],
   "execution_count": 9
  },
  {
   "cell_type": "code",
   "source": [
    "# 切片索引\n",
    "print(ser_obj.iloc[1:3])  #索引位置取数据，左闭右开\n",
    "print(ser_obj.loc['b':'d'])  #记住索引名  左闭右闭"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-01-07T06:27:09.288805Z",
     "start_time": "2025-01-07T06:27:09.285677Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b    1\n",
      "c    2\n",
      "dtype: int64\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "dtype: int64\n"
     ]
    }
   ],
   "execution_count": 8
  },
  {
   "cell_type": "code",
   "source": [
    "# 不连续索引\n",
    "print(ser_obj.iloc[[0, 2, 4]])\n",
    "print(ser_obj.loc[['a', 'e']])"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-01-17T04:51:00.607485Z",
     "start_time": "2025-01-17T04:51:00.603843Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    0\n",
      "c    2\n",
      "e    4\n",
      "dtype: int64\n",
      "a    0\n",
      "e    4\n",
      "dtype: int64\n"
     ]
    }
   ],
   "execution_count": 10
  },
  {
   "cell_type": "code",
   "source": [
    "# 布尔索引\n",
    "ser_bool = ser_obj > 2\n",
    "print(ser_obj)\n",
    "print(ser_bool)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-01-17T05:05:38.072623Z",
     "start_time": "2025-01-17T05:05:38.068695Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    0\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "e    4\n",
      "dtype: int64\n",
      "a    False\n",
      "b    False\n",
      "c    False\n",
      "d     True\n",
      "e     True\n",
      "dtype: bool\n"
     ]
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T05:06:34.013038Z",
     "start_time": "2025-01-17T05:06:34.009979Z"
    }
   },
   "cell_type": "code",
   "source": [
    "print(ser_obj[ser_bool])\n",
    "print(ser_obj[ser_obj > 2]) #取出大于2的元素"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "d    3\n",
      "e    4\n",
      "dtype: int64\n",
      "d    3\n",
      "e    4\n",
      "dtype: int64\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "cell_type": "markdown",
   "source": "##### 4.DataFrame索引",
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "source": [
    "# 1. columns 指定列索引名\n",
    "import numpy as np\n",
    "df_obj = pd.DataFrame(np.random.randn(5,4),\n",
    "                      columns = ['a', 'b', 'c', 'd'])\n",
    "print(df_obj.head())"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-01-17T05:09:12.439086Z",
     "start_time": "2025-01-17T05:09:12.435031Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "          a         b         c         d\n",
      "0  0.783247 -0.588637  1.451923  0.330594\n",
      "1  1.764410 -1.239934  1.072997 -0.455152\n",
      "2  0.328256  2.076115 -0.265541  0.771555\n",
      "3 -0.086867  1.993707  0.300196 -1.559831\n",
      "4  0.923000 -1.240787  1.711714 -1.858998\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "cell_type": "code",
   "source": [
    "# 2.列索引\n",
    "# 不规范写法\n",
    "print(df_obj['a']) # 返回Series类型\n",
    "print('-'*50)\n",
    "print(df_obj[['a']]) # 返回DataFrame类型\n",
    "print(type(df_obj[['a']]))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-01-17T05:10:11.093916Z",
     "start_time": "2025-01-17T05:10:11.090196Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    0.783247\n",
      "1    1.764410\n",
      "2    0.328256\n",
      "3   -0.086867\n",
      "4    0.923000\n",
      "Name: a, dtype: float64\n",
      "--------------------------------------------------\n",
      "          a\n",
      "0  0.783247\n",
      "1  1.764410\n",
      "2  0.328256\n",
      "3 -0.086867\n",
      "4  0.923000\n",
      "<class 'pandas.core.frame.DataFrame'>\n"
     ]
    }
   ],
   "execution_count": 15
  },
  {
   "cell_type": "markdown",
   "source": [
    "###### Pandas 的高级索引有 3 种\n",
    "###### 1. loc 标签索引(通过索引标签值获取数据)\n",
    "- DataFrame不能直接切片，可以通过loc来做切片"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "source": [
    "# 标签索引 loc，建议使用loc，效率更高\n",
    "# Series\n",
    "print(ser_obj)\n",
    "print(ser_obj['b':'d'])\n",
    "print(ser_obj.loc['b':'d']) #前闭后闭"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-01-17T05:14:05.419094Z",
     "start_time": "2025-01-17T05:14:05.415682Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    0\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "e    4\n",
      "dtype: int64\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "dtype: int64\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "dtype: int64\n"
     ]
    }
   ],
   "execution_count": 17
  },
  {
   "cell_type": "code",
   "source": [
    "# DataFrame\n",
    "df_obj = pd.DataFrame(np.random.randn(5,4),columns = list('abcd'),index=list('abcde'))\n",
    "print(df_obj)\n",
    "print('-'*50)\n",
    "print(df_obj['a'])  #建议不用,拿的是列\n",
    "print('-'*50)\n",
    "print(df_obj.loc['a'])  #拿的是行\n",
    "print('-'*50)\n"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-17T05:14:30.780895Z",
     "start_time": "2025-01-17T05:14:30.775836Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "          a         b         c         d\n",
      "a -1.191643  0.394029  0.235060 -0.815684\n",
      "b -0.053554 -0.431456  0.590187  0.565848\n",
      "c  0.578221  1.140406 -1.034130  1.787335\n",
      "d -0.959408  0.055632 -2.245013  1.371145\n",
      "e  0.075883  0.017180 -2.495709  2.985850\n",
      "--------------------------------------------------\n",
      "a   -1.191643\n",
      "b   -0.053554\n",
      "c    0.578221\n",
      "d   -0.959408\n",
      "e    0.075883\n",
      "Name: a, dtype: float64\n",
      "--------------------------------------------------\n",
      "a   -1.191643\n",
      "b    0.394029\n",
      "c    0.235060\n",
      "d   -0.815684\n",
      "Name: a, dtype: float64\n",
      "--------------------------------------------------\n"
     ]
    }
   ],
   "execution_count": 18
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T05:15:53.209487Z",
     "start_time": "2025-01-17T05:15:53.204546Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 第一个参数索引行，第二个参数是列,loc或者iloc效率高于直接用取下标的方式，前闭后闭\n",
    "print(df_obj.loc['a':'c', 'b':'d']) # 连续索引\n",
    "print(df_obj.loc[['a','c'], ['b','d']]) # 不连续索引\n",
    "print(df_obj.loc[['c'],['b']]) #取一个值,返回的是DataFrame类型\n",
    "print(df_obj.loc['c','b'])  #取一个值"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "          b         c         d\n",
      "a  0.394029  0.235060 -0.815684\n",
      "b -0.431456  0.590187  0.565848\n",
      "c  1.140406 -1.034130  1.787335\n",
      "          b         d\n",
      "a  0.394029 -0.815684\n",
      "c  1.140406  1.787335\n",
      "          b\n",
      "c  1.140406\n",
      "1.1404058251765699\n"
     ]
    }
   ],
   "execution_count": 19
  },
  {
   "cell_type": "markdown",
   "source": [
    "###### 2.iloc 位置索引(推荐使用)\n",
    "- 作用和 loc 一样，不过是基于索引编号来索引"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "source": [
    "# Series\n",
    "print(ser_obj)\n",
    "print(ser_obj[1:3])\n",
    "print('-'*50)\n",
    "print(ser_obj.iloc[1:3]) # 左闭右开[)，效率高\n"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-17T05:19:18.304786Z",
     "start_time": "2025-01-17T05:19:18.301311Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    0\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "e    4\n",
      "dtype: int64\n",
      "b    1\n",
      "c    2\n",
      "dtype: int64\n",
      "--------------------------------------------------\n",
      "b    1\n",
      "c    2\n",
      "dtype: int64\n"
     ]
    }
   ],
   "execution_count": 21
  },
  {
   "cell_type": "code",
   "source": [
    "# DataFrame，iloc是前闭后开[)\n",
    "print(df_obj)\n",
    "print('-'*50)\n",
    "print(df_obj.iloc[0:2, 0:2]) \n",
    "print('-'*50)\n",
    "print(df_obj.iloc[[0,2], [0,2]]) # 不连续索引\n",
    "print('-'*50)\n",
    "print(df_obj.iloc[0,0]) # 取一个值"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-01-17T05:20:14.700773Z",
     "start_time": "2025-01-17T05:20:14.695170Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "          a         b         c         d\n",
      "a -1.191643  0.394029  0.235060 -0.815684\n",
      "b -0.053554 -0.431456  0.590187  0.565848\n",
      "c  0.578221  1.140406 -1.034130  1.787335\n",
      "d -0.959408  0.055632 -2.245013  1.371145\n",
      "e  0.075883  0.017180 -2.495709  2.985850\n",
      "--------------------------------------------------\n",
      "          a         b\n",
      "a -1.191643  0.394029\n",
      "b -0.053554 -0.431456\n",
      "--------------------------------------------------\n",
      "          a        c\n",
      "a -1.191643  0.23506\n",
      "c  0.578221 -1.03413\n",
      "--------------------------------------------------\n",
      "-1.1916430342768376\n"
     ]
    }
   ],
   "execution_count": 23
  },
  {
   "cell_type": "code",
   "source": [
    "# 没有设置行和列索引的DataFrame，iloc和loc的区别\n",
    "df_obj2 = pd.DataFrame(np.random.randn(5,4))\n",
    "print(df_obj2)\n",
    "print('-'*50)\n",
    "print(df_obj2.iloc[0:2]) #左闭右开 2行\n",
    "print('-'*50)\n",
    "print(df_obj2.loc[0:2]) #左闭右闭 3行"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-01-17T05:21:39.001506Z",
     "start_time": "2025-01-17T05:21:38.994784Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "          0         1         2         3\n",
      "0 -1.245682 -0.791301 -0.064978 -0.218455\n",
      "1 -1.589617 -0.844228 -0.907427  1.503512\n",
      "2 -1.572476 -0.759190 -1.214075  1.125853\n",
      "3  0.562811 -0.039771  0.289694 -0.353882\n",
      "4 -1.252111  0.634259  0.306954  0.093736\n",
      "--------------------------------------------------\n",
      "          0         1         2         3\n",
      "0 -1.245682 -0.791301 -0.064978 -0.218455\n",
      "1 -1.589617 -0.844228 -0.907427  1.503512\n",
      "--------------------------------------------------\n",
      "          0         1         2         3\n",
      "0 -1.245682 -0.791301 -0.064978 -0.218455\n",
      "1 -1.589617 -0.844228 -0.907427  1.503512\n",
      "2 -1.572476 -0.759190 -1.214075  1.125853\n"
     ]
    }
   ],
   "execution_count": 24
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
